package DataStructure.tree.swordOffer;

import DataStructure.tree.TreeNode;

import java.util.*;

/**
 * 剑指 Offer 32 - III. 从上到下打印二叉树 III https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
 * 题目简述：按之字形打印二叉树，即奇数层正序打印，偶数层反序打印
 */
public class LevelOrder2 {

    /**
     * 思路：层序遍历。若为偶数层则将层列表反序输出到结果
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);//第一层
        boolean isOdd = true;
        while (!deque.isEmpty()) {
            int n = deque.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0;i < n;i++) {
                TreeNode node = deque.remove();
                level.add(node.val);
                if (node.left != null) deque.add(node.left);
                if (node.right != null) deque.add(node.right);
            }
            //若为偶数层则将列表反序输出
            if (!isOdd) Collections.reverse(level);
            result.add(level);
            isOdd = !isOdd;
        }
        return result;
    }
}
